package com.vincce.sport.core.weixin;

import org.apache.http.HttpHost;
import org.apache.http.client.fluent.Executor;
import org.apache.http.client.fluent.Form;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: henry
 * Date: 9/3/13
 * Time: 3:48 PM
 * To change this template use File | Settings | File Templates.
 */
public class HttpUtil {

	private static final String PROXY_IP = "84.238.29.37";
	private static final int PROXY_PORT = 808;
	private static final HttpHost PROXY_HOST = new HttpHost(PROXY_IP, PROXY_PORT);

	public static String fetch(Request request, Map<String, String> params) throws IOException {
		return fetch(request, params, "UTF-8");
	}

	public static String fetch(Request request, Map<String, String> params, String charset) throws IOException {
		Form form = Form.form();
		for (Map.Entry<String, String> entry : params.entrySet()) {
			form.add(entry.getKey(), entry.getValue());
		}
		return fetch(request.bodyForm(form.build(), Charset.forName(charset)));
	}

	public static String fetch(Request request, Form bodyForm) throws IOException {
		return fetch(request.bodyForm(bodyForm.build(), Charset.forName("UTF-8")));
	}

	public static String fetch(Request request, String bodyString) throws IOException {
		return fetch(request.bodyString(bodyString, ContentType.create("text/plain", "UTF-8")));
	}

	public static String fetch(Request request) throws IOException {
		//request.viaProxy(PROXY_HOST);
		Executor executor = Executor.newInstance();
		String result = executor.execute(request).returnContent().asString();
//		executor.clearCookies();
		return result;
	}

	public static InputStream fetchInputStream(Request request) throws IOException {
		Executor executor = Executor.newInstance();
		InputStream is = executor.execute(request).returnContent().asStream();
		executor.clearCookies();
		return is;
	}

}
